package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math"
	"math/rand"
	"os"
	"time"
)

func TestSleep() {
	fmt.Println("0")
	time.Sleep(time.Second * 5)
	fmt.Println("5")
}

func PrintTime() {
	// 2006-01-02 15:04:05 为固定写法
	var timeStr string = time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(timeStr)
}

func GetRand() {
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 10; i++ {
		r1 := rand.Intn(10)
		fmt.Println(r1)
	}
}
func TestMath() {
	fmt.Println(math.MaxInt)
	fmt.Println(math.MinInt)
	fmt.Println(math.E)
	var a float64 = math.Pow(2, 10)
	fmt.Println(a)
	var b float64 = math.Max(10, 2)
	var c float64 = math.Floor(2.3)
	var d float64 = math.Ceil(2.3)
	var e float64 = math.Sqrt(4)
	var f float64 = math.Abs(-4)
	fmt.Println(b, c, d, e, f)
}

type Person struct {
	Name string
	Age  int
}

func TestJson() {
	stu := Person{
		Name: "Jerry",
		Age:  123,
	}
	b, err := json.Marshal(stu)
	if err != nil {
		fmt.Printf("err:%v", err)
		return
	}
	fmt.Println(string(b))

	str := `{"Name":"Jack","Age":12}`
	var p2 Person
	json.Unmarshal([]byte(str), &p2)
	fmt.Println(p2.Name, p2.Age)
}

func ReadFileByLine() {
	file, _ := os.Open("test.txt")
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var count int
	for scanner.Scan() {
		count++
		// 读取当前行内容
		var line string = scanner.Text()
		fmt.Println(count, " - ", line)
	}
}

func ReadFileAll() {
	bytes, _ := ioutil.ReadFile("test.txt")
	fmt.Println(string(bytes))
}

func WriteFile() {
	file, _ := os.OpenFile("test2.txt", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0664)
	defer file.Close()
	//以字符串的形式写入
	file.WriteString("hello world, 你好，新年快乐\n")
	file.Sync()
}
